﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.Threading;
using System.Globalization;
using System.Resources;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using Framework.Library;
using Framework.Library.Components.Modules;
using Framework.Module.Language.Library;
using Framework.Module.Language.Library.DataAccess;

namespace Framework.Module.Language.Admin
{
    public partial class LanguageList : ModuleControlBase
    {
        public string val;
        public string currentFileName;
        TextWriter writeStream;
        DataTable table;
        public int rowChangeIndex;
        public string filePath;

        XPathDocument doc;
        public string name, value;
        public string localename, localekey;
        XmlNode node;

        protected void Page_Load(object sender, EventArgs e)
        {
            filePath = Path.GetDirectoryName(Server.MapPath(Library.GlobalVal.LangPath));
            val = filePath;
            LoadCbLocale();

            if (!IsPostBack)
            {
                LoadListResource(filePath);
            }
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            if (!e.Equals(""))
            {
                GridViewRow rowselect = GridView1.Rows[e.NewEditIndex];
                val = "";
                val = rowselect.Cells[1].Text;
                lblMsg.Text = val;
                Panel2.Visible = false;
                Panel1.Visible = true;
                currentFileName = filePath + "\\" + val;
                GetExtensionFile(currentFileName);
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            SaveFileExist(Label4.Text);
            lblMsg.Text = "File is saved complete";
        }
       
        private void CreateNewFile(string newName, string extension, string typeCreate)
        {
            FileInfo file = new FileInfo(Server.MapPath(GlobalVal.TemplateResource));

            string strSaveFile = MapPath(GlobalVal.LangPath + "//Lang." + newName + extension);

            if (typeCreate.Equals("Create"))
            {
                file.CopyTo(strSaveFile, false);
            }
           
        }
      
        public void LoadListResource(string filePath)
        {
            DataTable table = new DataTable("List");
            table.Columns.Add("File", typeof(string));

            //FIND ALL FILES IN FOLDER 
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(filePath);

            foreach (System.IO.FileInfo f in dir.GetFiles("*.*"))
            {
                string fileExtension = f.Extension.ToUpper();

                //LOAD FILES
                if (fileExtension.Equals(".RESX"))
                {
                    table.Rows.Add(f.Name);
                }
            }
            GridView1.DataSource = table.DefaultView;
            GridView1.DataBind();
        }
        public void GetExtensionFile(string fieldName)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fieldName);
            //lblText.Text = dir.ToString();
            if (File.Exists(fieldName))
            {
                lblMsg.Text = "dang doc file";
                FileInfo efInfo = new FileInfo(fieldName);
                string fext = efInfo.Extension.ToUpper();

                if (fext.Equals(".RESX"))
                {
                    GridView4.DataSource = ReadResxFile(fieldName);
                    GridView4.DataBind();
                }
              
                Label4.Text = fieldName;
            }
            else
            {
                lblMsg.Text = "Khong tim thay file";
            }
        }

        public DataTable ReadResxFile(string fieldName)
        {
            DataTable table = new DataTable("Resx");
            table.Columns.Add("name", typeof(string));
            table.Columns.Add("value", typeof(string));
            Boolean flag = false;
            try
            {
                doc = new XPathDocument(fieldName);
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }
            if (flag == true)
            {
                foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/data"))
                {

                    if (nav.NodeType.GetType() != XmlNodeType.Comment.GetType())
                    {
                        //name = nav.Select("data").Current.GetAttribute("name", string.Empty);
                        //value = nav.SelectSingleNode("value").Value;
                        //  table.Rows.Add(name, value);
                        table.Rows.Add(nav.Select("data").Current.GetAttribute("name", string.Empty), nav.SelectSingleNode("value").Value);//GetAttribute("Name",string.Empty);
                    }
                }
            }

            return table;
        }
        private void SaveFileExist(string currentFileName)
        {
            FileInfo efInfo = new FileInfo(currentFileName);
            string fext = efInfo.Extension.ToUpper();

            string FileName = Path.GetFileName(currentFileName);

            if (fext.Equals(".RESX"))
                WriteResXFile(currentFileName);
         
        }

        // Write a resource file for format xml
        private void WriteResXFile(string currentname)
        {
            Boolean flag = false;

            XmlDocument doc = new XmlDocument();
            doc.Load(currentname);
            flag = true;

            if (flag == true)
            {
                foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/data"))
                {
                    if (nav.NodeType.GetType() != XmlNodeType.Comment.GetType())
                    {
                        name = nav.Select("data").Current.GetAttribute("name", string.Empty);
                        value = nav.SelectSingleNode("value").Value;

                        updatenode(nav, name, value);
                    }
                }            
            }
            doc.Save(currentname);
        }
        void updatenode(XPathNavigator node, string node_att_name, string old_value)
        {
            Boolean f;
            for (int i = 0; i < GridView4.Rows.Count; i++)
            {
                string name_replace = GridView4.Rows[i].Cells[0].Text;
                TextBox txt = (TextBox)GridView4.Rows[i].FindControl("txt5");
                string value_replace = txt.Text;

                if (node_att_name.Equals(name_replace))
                {
                    foreach (XPathNavigator navigator in node.Select("value"))
                    {
                        if (navigator.Value.Contains("<br>"))
                        {
                            string str = navigator.Value;
                            str = str.Replace("<br>", "");
                            navigator.InnerXml = str;
                        }

                        if (navigator.Value.Equals(old_value))
                            navigator.InnerXml = value_replace;

                        // Response.Write("<br> "+ navigator.OuterXml);
                        break;
                    }
                }
                //return node;
            }

        }

        void LoadCbLocale()
        {
            table = new DataTable();
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath(GlobalVal.LocalesFile));

            table.Columns.Add("languagename", typeof(string));
            table.Columns.Add("languagekey", typeof(string));

            foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/language"))
            {
                if (nav.NodeType.GetType() != XmlNodeType.Comment.GetType())
                {
                    localename = nav.Select("language").Current.GetAttribute("name", string.Empty);
                    localekey = nav.Select("language").Current.GetAttribute("key", string.Empty);

                    table.Rows.Add(localename, localekey);
                    cbLanguage.Items.Add(new ListItem(localename, localekey));
                }
            }
        }

        Boolean InsertNewLocale(string name, string value)
        {
            LanguageDataAccess lang = new LanguageDataAccess();

            //-->false-->exist
            //-->true --> not exist
            if (!lang.CheckExistValue(name))
            {
                LanguageInfo lang_info = new LanguageInfo();
                lang_info.language_culture = name;
                lang_info.language_name = value;

                try
                {
                    lang.Insert(lang_info);
                    return true;
                }
                catch (Exception ex)
                {
                    Response.Write("<script language = javascript> alert (\" File is Exist.Change again!\")</script>");
                    return false;
                }
                // return true;
            }
            else
            {

                return false;
            }
        }

        protected void cmdAdd_Click(object sender, EventArgs e)
        {
           // Response.End();
            if (cbLanguage.SelectedIndex != -1)
            {
                string strValue = cbLanguage.SelectedValue;
                string strName = cbLanguage.SelectedItem.Text;

                if (InsertNewLocale(strValue, strName))
                {
                    CreateNewFile(strValue, GlobalVal.StrExtension, "Create");
                }
                else
                {
                    Response.Write("<script language = javascript> alert (\" File is Exist.Change again!\")</script>");
                }
                
                LoadListResource(filePath);
            }
        }
        void RemoveFileLanguage(string fileRemove)
        {
            FileInfo file = new FileInfo(Server.MapPath(fileRemove));
            file.Delete();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (!e.Equals(""))
            {
                GridViewRow rowselected = GridView1.Rows[e.RowIndex];

                val = rowselected.Cells[1].Text;
                Response.Write(val);
                //lblMsg.Text = val;

                val = GetLanguageCulture(val);

                string filePathRemove = GlobalVal.LangPath + "Lang." + val + ".resx";

                //xoa trong database
                LanguageDataAccess lang = new LanguageDataAccess();
                
                
                lang.Delete(val);

                //xoa trong thu muc chua ngon ngu
                RemoveFileLanguage(filePathRemove);
                LoadListResource(filePath);
            }
        }
        protected string GetLanguageCulture(string fileName)
        {
            string[] strName = fileName.Split('.');
            int i = strName.Length;

            if ((strName[i - 1]).Equals("resx") || (strName[i - 1].Equals("resources")))
            {
                return strName[i - 2].ToString();
            }
            else
                return string.Empty;

        }

   
        
    }
    
}